package linwen.wang.jdbc;



import org.apache.commons.lang.time.StopWatch;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcInsert {
    public static void main(String[] args) {
        conn();
    }

    private static void conn() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try{
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wlw_dev?" + "&rewriteBatchedStatements=true","root","123456789");
            //4.定义sql语句
            String sql = "insert into batch_insert_t(id,name,gender,number,address,created_by,last_updated_by,del_flag)" +
                    " values(default,?,?,?,?,?,?,?)";
            //5.获取执行sql的对象PreparedStatement
            pstmt = conn.prepareStatement(sql);
            //6.不断产生sql
            for (int i = 0; i < 80000; i++) {
                pstmt.setString(1,"张三"+(int)(Math.random()*10000));
                pstmt.setString(2,((int)(Math.random()*10)%2==0?"男":"女"));
                pstmt.setString(3,(Math.random()*10000)+"");
                pstmt.setString(4,"广东深圳");
                pstmt.setString(5,"李四"+(int)(Math.random()*10000));
                pstmt.setString(6,"李四"+(int)(Math.random()*10000));
                pstmt.setString(7,"N");
                pstmt.addBatch();
            }
            System.out.println("产生sql时间  "+stopWatch.getTime());
            stopWatch.reset();
            //7.往数据库插入一次数据
            stopWatch.start();
            pstmt.executeBatch();
            System.out.println("执行sql时间 "+stopWatch.getTime());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //8.释放资源
            //避免空指针异常
            if(pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
